﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ShopBLL;
using ShopModel;
using System.Net.Mail;
using System.Net;
using System.Text;
using ASP;

public partial class ProductDetail : BasePage
{
    #region CONSTANTS

    private const int MAX_AUTHOR_LENGTH = 50;
    private const int MAX_CONTENT_LENGTH = 500;
    private const int COLUMN = 6;

    #endregion CONSTANTS

    #region VARIABLES

    protected int _ProductID;
    protected Products _Product;

    #endregion VARIABLES

    #region METHODS

    private void ShowError(string massage, bool isError)
    {
        lblErrorComment.Text = massage + "<br />";
        lblErrorComment.Visible = true;
        if (isError)
        {
            lblErrorComment.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblErrorComment.ForeColor = System.Drawing.Color.Green;
        }
    }

    private void GenerateImages(List<PictureInfo> Pictures)
    {
        dlPictures.DataSource = Pictures;
        dlPictures.DataBind();
    }

    private void GeneratePropertyPanel(List<ProductProperty> Properties)
    {
        List<ProductProperty> result = new List<ProductProperty>();
        bool newRow = true;
        Dictionary<int, ProductProperty> multiPropertyCells = new Dictionary<int, ProductProperty>();
        ProductProperty proper;

        foreach (ProductProperty current in Properties)
        {

            if (current.TypeOfProperty == PropertyType.MultiDictionary && multiPropertyCells.ContainsKey(current.Id))
            {
                proper = multiPropertyCells[current.Id];
                newRow = false;
            }
            else
            {
                proper = new ProductProperty();
                newRow = true;
                proper.Name = current.Name;
                proper.Id = current.Id;
                if (current.TypeOfProperty == PropertyType.MultiDictionary)
                {
                    multiPropertyCells.Add(current.Id, proper);
                }
            }

            if (current.TypeOfProperty == PropertyType.Numeric)
            {
                proper.Value = current.NumericValue.ToString();
            }
            else if (current.TypeOfProperty == PropertyType.MultiDictionary && !newRow)
            {
                proper.Value += "<br /> " + current.Value;
            }
            else
            {
                proper.Value = current.Value;
            }

            if (newRow)
            {
                result.Add(proper);
            }
        }

        rptProperty.DataSource = result;
        rptProperty.DataBind();
    }

    private void BindComments()
    {
        gvComment.DataSource = ProductsManager.Instance.GetCommentForProduct(_ProductID, false);
        gvComment.DataBind();

        decimal avgrate = ProductsManager.Instance.GetAvgRateForProduct(_ProductID);
        lAvgRate.Text = avgrate == ((decimal)0) ? Resources.Language.ProductNotRated : avgrate.ToString("F");
    }

    private void BindDocuments()
    {
        rptDocuments.DataSource = _Product.Documents;
        rptDocuments.DataBind();
    }

    private void BindVideos()
    {
        rptVideos.DataSource = _Product.Videos;
        rptVideos.DataBind();
    }

    #endregion METHODS

    #region EVENTS

    protected void btnSendReccomendation_Click(object sender, EventArgs e)
    {
        string refferer = tbRefferer.Text;
        string email = tbFriendEmail.Text;
        string content = tbContent.Text;

        Validate("Reffer");
        if (Page.IsValid)
        {
            MailMessage _Message;
            SmtpClient _SmtpClient = new SmtpClient(ShopModel.Settings.CompanyMailHost);

            _SmtpClient.Credentials = new NetworkCredential(ShopModel.Settings.CompanyMailLogin, ShopModel.Settings.CompanyMailPassword);
            _SmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

            _Message = new MailMessage();
            _Message.From = new MailAddress(ShopModel.Settings.CompanyEmail, refferer, Encoding.UTF8);
            _Message.To.Add(new MailAddress(email));
            _Message.Subject = string.Format(Resources.Language.ProductDetailMessage1, refferer, _Product.Name);

            _Message.IsBodyHtml = true;
            _Message.Body = string.Format("{0}<br /><br /><a href=\"{1}\">{2}</a>", content, this.Request.Url.AbsoluteUri.Remove(this.Request.Url.AbsoluteUri.IndexOf("ProductDetail")) + Request.QueryString["ProductId"] + "," + Resources.Language.Product.ToLower() + ".aspx", Resources.Language.RecommendationLink);

            _SmtpClient.Send(_Message);
            tbRefferer.Text = string.Empty;
            tbFriendEmail.Text = string.Empty;
            tbContent.Text = string.Empty;

            //GeneratePropertyPanel(_Product.PropertyList);
            //GenerateImages(_Product.Pictures);
            //BindComments();
            pnlReccomentInside1.Style[HtmlTextWriterStyle.Display] = "none";
            pnlReccomentInside2.Style[HtmlTextWriterStyle.Display] = "block";
            //pRecommendProduct.Style[HtmlTextWriterStyle.Display] = "none";
        }
    }

    protected void btnAddComment_Click(object sender, EventArgs e)
    {
        //Validate("Comment");
        //if (IsValid)
        {
            if (txtAuthor.Text.Length > MAX_AUTHOR_LENGTH)
            {
                ShowError(string.Format(Resources.Language.Error_ToLong, Resources.Language.Author, MAX_AUTHOR_LENGTH), true);
                txtAuthor.Text = txtAuthor.Text.Substring(0, MAX_AUTHOR_LENGTH);
            }
            else if (txtContent.Text.Length > MAX_CONTENT_LENGTH)
            {
                ShowError(string.Format(Resources.Language.Error_ToLong, Resources.Language.Content, MAX_CONTENT_LENGTH), true);
                txtContent.Text = txtContent.Text.Substring(0, MAX_CONTENT_LENGTH);
            }
            else if (ProductsManager.Instance.AddCommentToProduct(new Comment(-1, txtAuthor.Text, txtContent.Text, DateTime.Now, Convert.ToDecimal(ddlRate.SelectedValue)), _ProductID))
            {
                txtContent.Text = string.Empty;
                txtAuthor.Text = string.Empty;
                ShowError(Resources.Language.CommentAdded, false);
            }
            else
            {
                ShowError(Resources.Language.Error_PleaseTryLater, true);
            }

            BindComments();
        }
    }

    protected void gvComment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvComment.PageIndex = e.NewPageIndex;
        BindComments();
    }

    protected void pcmSelectedProducts_Changed(object sender, EventArgs e)
    {
        if (this.Page.Master is _default)
        {
            if (Settings.ShowProductsToCompare)
            {
                controls_ctrlProductsToCompare ComparedProducts = (controls_ctrlProductsToCompare)(((_default)this.Master).FindControl("ctrlProductsToCompare"));

                if (ComparedProducts != null && ComparedProducts.BindControl)
                    ComparedProducts.ProductsBind();
            }
        }
    }

    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Init(object sender, EventArgs e)
    {
        _ProductID = Convert.ToInt32(Request.QueryString["ProductId"]);
        ctrlCrossSell1.ProductId = _ProductID;
        pcmSelectedProducts.ProductID = _ProductID;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        _ProductID = Convert.ToInt32(Request.QueryString["ProductId"]);
        _Product = ProductsManager.Instance.GetProduct(_ProductID, ShopBLL.CommonTools.CurrentLanguageID);

        if (Master is _default && _Product != null)
        {
            (Master as _default).ProductMetaTag = _Product.MetaTags;
        }

        if (!IsPostBack)
        {

            pPriceChangesGraph.Style[HtmlTextWriterStyle.Display] = "none";
            ctrlPriceChangeGraph1.ProductID = _ProductID.ToString();
            if (_Product != null)
            {
                aAddToBasket.Attributes.Add("onclick", "addToBasket(" + _ProductID.ToString() + "); return false;");

                if (this.Master is _default)
                {
                    ((_default)this.Master).OpenCategoryId = _Product.CategoryID; //otwarcie menu na obecnej kategorii
                }
                ctrlShowAvailableCount.AvailableCount = _Product.AvailableCount;
                ctrlShowAvailableCount.OnDemand = _Product.OnDemand;
                GeneratePropertyPanel(_Product.PropertyList);
                GenerateImages(_Product.Pictures);
                BindComments();
                BindDocuments();
                BindVideos();

                txtAuthor.MaxLength = MAX_AUTHOR_LENGTH;

                valRequireAuthor.ErrorMessage = Resources.Language.RequireField;
                valRequireRate.ErrorMessage = Resources.Language.RequireField;
                valRequireContent.ErrorMessage = Resources.Language.RequireField + "<br />";

                if (Session["BackUrl"] != null)
                {
                    ViewState["BackUrl"] = Session["BackUrl"];
                    Session["BackUrl"] = null;
                }
                else
                    if (ViewState["BackUrl"] == null)
                    {
                        ViewState["BackUrl"] = _Product.CategoryID.ToString() + "," + Resources.Language.Category.ToLower() + ".aspx";
                    }
            }
            else
            {
                Response.Redirect(Resources.Language.UrlProductError.ToLower() + ".aspx");
            }
            pnlReccomentInside2.Style[HtmlTextWriterStyle.Display] = "none";
        }
    }

    void Page_PreRender(object sender, EventArgs e)
    {
        btnOKReccoment.OnClientClick = string.Format("$('#{0}')[0].style.display = 'none'; $('#{1}')[0].style.display = ''; $('#{2}')[0].style.display = 'none'; return false;", pnlReccomentInside2.ClientID, pnlReccomentInside1.ClientID, pRecommendProduct.ClientID);
        ClientScript.RegisterStartupScript(this.GetType(), "StartupScript", string.Format("<script type=\"text/javascript\">SetElement_ProductDetail('{0}', '{1}', '{2}');</script>", tbRefferer.ClientID, tbFriendEmail.ClientID, tbContent.ClientID));
        ctrlShowAvailableCount.Visible = Settings.ShowAvailableCount;
    }

    #endregion PAGE EVENTS
}
